package cn.flying.cloud.esb.core.camel.process;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.Rt;
import cn.flying.cloud.esb.core.exception.EsbException;

/**
 * 全局异常处理器
 *
 * @author: admin
 * @date: 2025年04月12日 17:05
 * @version: 1.0
 */
@Component
public class ExceptionProcessor implements Processor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Processes the message exchange
     *
     * @param exchange the message exchange
     * @throws Exception if an internal processing error has occurred.
     */
    @Override
    public void process(Exchange exchange) throws Exception {
        // TODO 保存异常日志
        Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
        logger.error("", exception);

        if (exception instanceof EsbException) {
            EsbException e = (EsbException) exception;
            exchange.getMessage().setBody(Ft.JSON.serializer(Rt.error(e.getCode(), e.getMessage())));
        } else {
            exchange.getMessage().setBody(Ft.JSON.serializer(Rt.error("9999", exception.getMessage())));
        }
    }
}
